class Solution {
    vector<vector<int>> ret;
    vector<int> path;
    int target;
    void dfs(vector<int> &nums, int pos, int sum)
    {
        if(sum >= target || pos >= nums.size())
        {
            if(sum == target)
                ret.push_back(path);
            return;
        }

        // 解法二
        // 枚举nums[pos]这个数选多少次
        for(int k = 0; k * nums[pos] + sum <= target; k++)
        {
            if(k)
                path.push_back(nums[pos]);
            dfs(nums, pos + 1, sum + k * nums[pos]);
        }

        // 恢复现场
        for(int k = 1; k * nums[pos] + sum <= target; k++)
        {
            path.pop_back();
        }

        // 解法一
        // for(int i = pos; i < nums.size(); i++)
        // {
        //     path.push_back(nums[i]);
        //     dfs(nums, i, sum + nums[i]);
        //     path.pop_back();
        // }
    }
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int _target) {
        target = _target;
        dfs(candidates, 0, 0);
        return ret;
    }
};